<template>
  <div>
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      width="500"
    >
      <el-form style="width: 80%" :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- upload组件相应属性
             1.action：上传文件地址
             2.show-file-list:是否显示上传状态
             3.before-upload：限制文件格式和大小
        -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <!-- 如果logoUrl存在，则显示图片，若不存在，则显示icon -->
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reqADDOrUpdataTradmark } from "@/api/product/trademark";
import {
  dialogFormVisible,
  trademarkParams,
  formRef,
  getHasTrademark,
  pageNo,
} from "../index";
import { UploadProps, ElMessage } from "element-plus";
//文件上传成功服务器返回数据钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  //response:post请求返回数据
  //uploadFile:返回详细数据信息
  response,
) => {
  trademarkParams.logoUrl = response.data;
  //图片上传成功，去除错误提示信息
  formRef.value.clearValidata("logoUrl");
};
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  //钩子是在图片上传之前触发，上传文件之前可以约束文件类型与大小
  //rawFile:文件对象
  //要求：格式png|gif|jpg 4M
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传大小应小于4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件格式务必是PNG|GIF|JPG",
    });
    return false;
  }
};
//对话框取消按钮
const cancel = () => {
  formRef.value.clearValidate("tmName");
  formRef.value.clearValidate("logoUrl");
  dialogFormVisible.value = false;
};
//对话框确定按钮
const confirm = async () => {
  //再发请求之前对表单进行校验
  //调用这个方法进行表单校验，
  await formRef.value.validate();
  let result = await reqADDOrUpdataTradmark(trademarkParams);
  console.log(result);
  if (result.code == 200) {
    dialogFormVisible.value = false;
    ElMessage({
      type: "success",
      message: trademarkParams.id ? "品牌修改成功" : "品牌添加成功",
    });
    //再次发请求获取已有全部品牌
    if (trademarkParams.id) {
      console.log(trademarkParams.id);
      getHasTrademark(trademarkParams.id ? pageNo.value : 1);
    }
  } else {
    dialogFormVisible.value = false;
    ElMessage({
      type: "error",
      message: trademarkParams.id ? "品牌修改失败" : "品牌添加失败",
    });
  }
};
//品牌自定义校验规则方法
const validatorTmName = (_rule: any, value: any, callBack: any) => {
  // rule:表单规则对象
  //value:输入的值
  //callBack:放行函数
  //执行时机
  if (value.trim().length >= 2) {
    callBack();
    //成功
  } else {
    //失败
    //校验未通过返回错误的信息
    callBack(new Error("品牌名称长度大于两位 "));
  }
};
//品牌Logo自定义校验规则
//在未使用的属性前加；'_'前缀
const validatorLogoUrl = (_rule: any, value: any, callBack: any) => {
  //value:图片地址（验证是否有上传图片）
  //
  console.log(value);
  if (value) {
    callBack();
    //成功
  } else {
    //失败
    //校验未通过返回错误的信息
    callBack(new Error("LOGO不可为空"));
  }
};
//表单校验规则
const rules = {
  tmName: [
    //required：必须校验
    //trigger:校验时机（blur|change）
    //
    { required: true, trigger: "blur", validator: validatorTmName },
  ],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
